//
//  LCComposeView.swift
//  SinaWeiBo
//
//  Created by mac on 16/12/11.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import pop

class LCComposeView: UIView {
    
    //懒加载一个imageview
    private lazy var imageView: UIImageView = UIImageView()
    
    private lazy var buttonArray:[LCComposeButton] = [LCComposeButton]()
    
    //定义一个变量来记录传递过来的tabbar控制器
    private var tagetVc:UIViewController?
   
    //懒加载一个模型数组
    private lazy var composeModelList:[LCComposeModel] = self.loadComposePlistData()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        addSubview(imageView)
        
        //添加button
        childComposeButton()
        //执行button动画
        startButtonAnimation(isup: true)
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        //处理模糊效果
        imageView.image = screenShot().applyLightEffect()
        
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        startButtonAnimation(isup: false)
        //延时
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {() -> Void in
            self.removeFromSuperview()
        
        })

    }
    
    //截屏操作
    func screenShot() -> UIImage {
        
        //  开启图片上下文
        let window = UIApplication.shared.keyWindow!
        UIGraphicsBeginImageContext(window.size)
        
        //  截图操作
        //  是否等到屏幕更新去截图
        //  rect表示截取的区域
        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.size), afterScreenUpdates: false)
        //  在图片上下文中获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //  结束图片上下文
        UIGraphicsEndImageContext()
        return image!

    }

     //提供一个方法来创建6个button
    private func childComposeButton(){
        //button的大小
        let buttonWidht: CGFloat = 80
        let buttonHeight: CGFloat = 100
        
        //button之间的间距
        let buttonMargin = (wigth - 3*buttonWidht)/4
        
        for i in 0..<composeModelList.count{
            
            //算出每一个button对应的行数和列数
            //列数
            let row = i%3
            //行数
            let line = i/3
            
            let composeButton = LCComposeButton()
            
            //给button加一个tag方便后面使用tag来从模型数组中取出对应模型
            composeButton.tag = i
            //取出模型
            let model = composeModelList[i]
            
            //添加button的点击事件
            composeButton.addTarget(self, action: #selector(buttonAction(btn:)), for: .touchUpInside)
            composeButton.setImage(UIImage(named: model.icon!), for: .normal)
            composeButton.setTitle(model.title, for: .normal)
            composeButton.size = CGSize(width: buttonWidht, height: buttonHeight)
            //根据行数和列数来算出每一个button对应的坐标
            composeButton.x = CGFloat(row)*buttonWidht + CGFloat(row+1)*buttonMargin
            composeButton.y = CGFloat(line)*buttonHeight + CGFloat(line)*buttonMargin + height
            
            addSubview(composeButton)
            buttonArray.append(composeButton)
        }

    }
    
    //读取本地plist文件
    private func loadComposePlistData() -> [LCComposeModel]{
        //1获取路径
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)
        //2获取路径中的数据
        let composeArray = NSArray(contentsOfFile: path!) as! [[String:Any]]
        //3字典转模型
        let modelList = NSArray.yy_modelArray(with: LCComposeModel.self, json: composeArray) as! [LCComposeModel]
        return modelList
    }
    
    //button的点击事件
    @objc private func buttonAction(btn: LCComposeButton){
        
        UIView.animate(withDuration: 0.3, animations: {
            for button in self.buttonArray{
                if button == btn{
                    button.transform = CGAffineTransform(scaleX: 1.6, y: 1.6)
                }else{
                    button.alpha = 0.3
                    button.transform = CGAffineTransform(scaleX: 0.4, y: 0.4)
                }
            }
        }, completion: {(_) in
            UIView.animate(withDuration: 0.3, animations: { 
                for button in self.buttonArray{
                    button.transform = CGAffineTransform.identity
                    button.alpha = 1
                }
            }, completion: { (_) in
                //弹出发微博的控制器
                //  HMComposeViewController
                //  问题1- 直接通过(自定义的)类名获取class 不可以,打印nil -> 需要加上命名空间
                //  通过类型获取类名字符串(Weibo22.HMComposeViewController), 自定义的类获取的类名会有这个命名空间
                //  let aa = NSStringFromClass(HMComposeViewController.self)
                //  print(aa)

                //  转成指定类型,然后创建实例
                let model = self.composeModelList[btn.tag]
                
                let classType = NSClassFromString(model.className!) as! UIViewController.Type
                
                //  创建实例
                let vc = classType.init()
                let navc = LCNavigationController(rootViewController: vc)
                
                self.tagetVc?.present(navc, animated: true, completion: {
                    //模态出来发微博控制器以后，就把模糊效果的view移除掉
                    self.removeFromSuperview()
                    
                })
            })
        })
        
    }
    
    //定义一个show方法，作用是，将tabar控制器传递过来
    func show(taget:UIViewController){
        //赋值
        self.tagetVc = taget
        //在这个地方就不能再将模糊view添加到window上面了，如果添加到window上面，你再模态出来的控制将显示不出来。
        //解决方法:可以将模糊view添加到传过来tabbar控制器的view上,让tabbar控制器去模态发微博的控制器
        taget.view.addSubview(self)
        
    }
    
    private func startButtonAnimation(isup:Bool){
        if isup == false {
            buttonArray = buttonArray.reversed()
        }
        
        //遍历button数组
        for (i,button) in buttonArray.enumerated(){
            //  创建弹簧动画对象
            let popSpringAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            if isup {
//                //  动画执行的目的地
                popSpringAnimation?.toValue = CGPoint(x: button.centerX, y: button.centerY - 350)
            } else {
                //  动画执行的目的地
                popSpringAnimation?.toValue = CGPoint(x: button.centerX, y: button.centerY + 350)
            }
            
            //  设置弹簧抖动幅度 [0-20]
            popSpringAnimation?.springBounciness = 10
            //  设置弹簧初始速度 [0-20]
            popSpringAnimation?.springSpeed = 10
            //  设置开始时间,完成动画的时间间隔
            //  CACurrentMediaTime 系统的绝对时间->(开机的时间距离现在的一个时间差)
            popSpringAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.08
            //  执行动画
            button.pop_add(popSpringAnimation, forKey: nil)
            
        }
        
    }
    
    
}
